/*************************************************
 *FileName:      editdata.js
 *Description:   编辑个人资料.js
 *Others:        陈灿
 *************************************************/
    /*
     * 启动
     */

    mui.init({
      gestureConfig:{
       tap: true, //默认为true
       doubletap: true, //默认为false
       longtap: true, //默认为false
       swipe: true, //默认为true
       drag: true, //默认为true
       hold:false,//默认为false，不监听
       release:false//默认为false，不监听
      }
    });
    mui.init({
        beforeback: function() {
            var list = plus.webview.currentWebview().opener();
            mui.fire(list, 'refreshindex');
            return true;
        }
    });
    /*
     * 变量初始化
     */
    var uid = localStorage.replace_uid;
    var token = localStorage.replace_token;
    var face='' ,nickname='',birthday='',height='',weight='',industry='',work_field='',company='',home_province='',home_city='',home_district='',place='',tags='',interest=[],imgs=[];
    var opper;
    var cropper = null  // 图片裁剪器
    var uplodeBlock = false //  阻止重复提交
    /*
     * 主程序
     */
    $(document).ready(function()
    {
        //样式加载
        pagecss();
    });
    //窗口大小监听事件
    $(window).resize(function() {
      $('.mui-dtpicker').toggle();
    });
    /**
     * pagecss
     * 样式加载
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    function pagecss(){
        mui.plusReady(msglode)
        $('.editdata .add-img').on('tap',function(){
            captureImage();
            $('.editdata .box-img').length>=30 ? $(this).remove(): false;
        })

        $('.mui-content').on('tap','input',function(){
            var othis =$(this);
            $(this).focusin();
            $('.mui-content').on('tap',function(){
                othis.blur();
            })
        })
        var ot , oh , ow;
        $('.mui-content').on('input','.nickname',function(){
            $(this).val().length>14 ? $(this).val(ot) :  ot =  $(this).val();
        })
        $('.mui-content').on('input','.height',function(){
            $(this).val().length>3 ? $(this).val(oh) :  oh =  $(this).val();
        })
        $('.mui-content').on('input','.weight',function(){
            $(this).val().length>3 ? $(this).val(ow) :  ow =  $(this).val();
        })

        //input输入的时候输入框跟着弹上去
        $('input').on('click', function () {
         var target = this;
            $(".mui-content").css('-webkit-overflow-scrolling','auto');
          setTimeout(function(){
           target.scrollIntoViewIfNeeded();
            $(".mui-content").css('-webkit-overflow-scrolling','touch');
           console.log('scrollIntoViewIfNeeded');
         },400);
        });

        var ov2a ;
        $('.work-message').on('tap',function(){
            oindex =$(this).index();
            $('.table-view2').fadeIn();
            $('.popover-img').css({display:'block'});
            labellard($(this),oindex+1)
            $('.table-view2 .table-con').on('tap','.table-view-cell-a',function(){
                ov2a=$(this).text();
                $('.table-view').fadeOut();
                $('.popover-img').css({display:'none'});
                $('.work-message').eq(oindex).text(ov2a);
                oindex==0 ?industry =$(this).attr('data-cateid') : work_field = $(this).attr('data-cateid');
            })
        })

        var oindex;
        $('.editdata').on('tap','.inf',function(){
            $('.table-view').fadeOut();
            oindex =$(this).index();
            $('.popover-img').css({display:'block'});
            if(oindex==2){
                $('.table-view-cell-input').attr('placeholder','添加公司信息');
            }else if(oindex==4 ){
                $('.table-view-cell-input').attr('placeholder','添加你常去的地方');
            }else{
                $('.table-view-cell-input').attr('placeholder','创建你的标签');
            }
            $('.table-view1').fadeIn();
        })

        $('.table-view1 .table-view-cell-affirm').on('tap',function(){
            if($('.table-view-cell-input').val()){
                if(oindex==2){
                    $('.inf.com-inf').text($('.table-view-cell-input').val());
                    company=$('.table-view-cell-input').val();
                }else if(oindex==4){
                    $('.inf.ads-inf').text($('.table-view-cell-input').val());
                    place=$('.table-view-cell-input').val();
                }else{
                    $('.table-con').append('<a class="table-view-cell-a active" data-cateid="'+$('.table-view-cell-input').val()+'" ><em class="ocheckbox"></em>'+$('.table-view-cell-input').val()+'</a>');
                    $('.table-view3').fadeIn();
                }
                $('.table-view1').fadeOut();
                $('.popover-img').css({display:'none'});
            }
            $('.table-view-cell-input').val(null);
        })

        $('.table-view1 .table-view-cell-a').on('tap',function(){
           $('.table-view-cell-input').blur();
        })

        $('.table-view-cell-cancel').on('tap',function(){
            $('.table-view').fadeOut();
            $('.popover-img').css({display:'none'});
        })


        $('.table-view3 .table-con').on('tap','.table-view-cell-a',function(){
            $(this).toggleClass('active');
        })


        var obiaoqianp;
        $('.editdata').on('tap','.biaoqian-p',function(){

            obiaoqianp=$(this);
            if($(this).attr('id')=='tags'){
                labellard(obiaoqianp,'9');
            }else{
                labellard(obiaoqianp,obiaoqianp.parent().index()+3);
            }
        })

        $('.table-view3 ').on('tap','.table-view-cell-affirm',function(){
            var olabel='';
            var arr=[];
            $(".table-view3 .table-con .active").each(function(){
                olabel+='<a data-id="'+$(this).attr('data-cateid')+'">'+$(this).text()+'</a>';
                arr.push($(this).attr('data-cateid'));
            });
            if(olabel==''){
                obiaoqianp.find('.bq-span').css({display:'block'})
            }else{
                obiaoqianp.find('.bq-span').css({display:'none'})
            }
            obiaoqianp.find('.bq-a').html(olabel);
            $('.table-view3').fadeOut();
            $('.popover-img').css({display:'none'});
            var oid =obiaoqianp.attr('id');
            if(obiaoqianp.attr('id')=='tags'){
                tags=arr;
            }
        })


        var _getParam = function(obj, param) {return obj[param] || '';};
        var cityPicker3 = new mui.PopPicker({layer: 3});
        cityPicker3.setData(cityData3);
        $('.ads').on('tap', function(e) {
            cityPicker3.show(function(items) {
                home_province = _getParam(items[0], 'text');
                home_city = _getParam(items[1], 'text');
                home_district = _getParam(items[2], 'text');
                $('.ads').text(home_province+'-'+home_city+'-'+home_district);
            });
        })

        // 代理 裁剪操作
        $('.img-cut').on('tap', '.cut-back', function() {
          closeImgCut()
        })
        $('.img-cut').on('tap', '.cut-confirm', function() {
          if (cropper) {
            var dataURL = cropper.getCroppedCanvas({
              fillColor: '#fff',
              imageSmoothingEnabled: false,
              imageSmoothingQuality: 'low',
            }).toDataURL('image/jpeg')

            uplode(dataURL)
          }
        })
    }
    /**
     *
     * mui框架时间样式
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    (function($) {
        $.init();
        var result = $('#demo2')[0];
        var btns = $('.btn');
        btns.each(function(i, btn) {
            btn.addEventListener('tap', function() {
                var _self = this;
                if(_self.picker) {
                    _self.picker.show(function (rs) {
                        result.value = rs.text;
                        _self.picker.dispose();
                        _self.picker = null;
                    });
                } else {
                    var optionsJson = this.getAttribute('data-options') || '{}';
                    var options = JSON.parse(optionsJson);
                    var id = this.getAttribute('id');
                    _self.picker = new $.DtPicker(options);
                    _self.picker.show(function(rs) {
                        result.value = rs.text;
                        _self.picker.dispose();
                        _self.picker = null;
                    });
                }
            }, false);
        });
    })(mui);


     /**
     * msglode
     * 信息加载
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    function msglode(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/personalData",
            dataType: 'jsonp',
            data: {
                uid: uid,
                token: token
            },
            success: function(data) {
                if(data.error_code == 0) {
                    data.data.sex=='man' ? $('.sex').val('男'): $('.sex').val('女');
                    for(var i=0; i<data.data.imgs.length ; i++){
                        $('.add-img').before('<div class="box-img" data-imgid="'+data.data.imgs[i].id+'"><img src="'+DOMAIN_NAME+data.data.imgs[i].url+'"></div>');
                    }
                    $('.mobile').val(data.data.mobile);
                    $('.nickname').val(data.data.nickname);
                    data.data.birthday ? $('.birthday').val(data.data.birthday):null;
                    data.data.height ? $('.height').val(data.data.height): null;
                    data.data.weight ? $('.weight').val(data.data.weight): null;
                    data.data.industry? $('.industry').text(data.data.industry.name) : null;
                    industry=data.data.industry.cateid;
                    data.data.work_field ? $('.work_field').text(data.data.work_field.name):null;
                    work_field=data.data.work_field.cateid;
                    if(data.data.home_province){
                        $('.ads').text(data.data.home_province+'-'+data.data.home_city+'-'+data.data.home_district);
                        home_province=data.data.home_province;
                        home_city=data.data.home_city;
                        home_district=data.data.home_district;
                    }
                    data.data.company ? $('.company').text(data.data.company):null;
                    company=data.data.company;
                    data.data.place ? $('.place').text(data.data.place):null;
                    place=data.data.place
                    if(data.data.tags){
                        var arr=[],otags='';
                        for(var i =0 ; i<data.data.tags.length ; i++){
                            data.data.tags[i].name ?otags+='<a>'+data.data.tags[i].name+'</a>' : otags+='<a>'+data.data.tags[i].content+'</a>';
                            arr.push(data.data.tags[i].content);
                        }
                        $('#tags .bq-span').css({display:'none'});
                        $('#tags .bq-a').html(otags);
                        tags=arr;
                    }
                    if(data.data.interest){
                        for(var i =0 ; i<data.data.interest.length ; i++){
                            var obqname = data.data.interest[i].name ? data.data.interest[i].name :data.data.interest[i].content;
                            $('.con-lick li').eq(data.data.interest[i].type-3).find('.bq-span').css({display:'none'});
                            $('.con-lick li').eq(data.data.interest[i].type-3).find('.bq-a').append('<a data-id="'+data.data.interest[i].content+'">'+obqname+'</a>');
                        }
                    }
                } else if(data.error_code == 1001) {
                    setTimeout(function() {
                        exitlogin();
                    },1000);
                } else {

                }
            }
        });
    }
     /**
     *
     * 保存编辑
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    $('.save').on('tap',function(){
        for(var i=0 ; i<$('.add-box .box-img').length ; i++ ){
            imgs.push($('.add-box .box-img').eq(i).attr('data-imgid'));
        }
        nickname=$('.nickname').val();
        birthday=$('.birthday').val();
        height=$('.height').val();
        weight=$('.weight').val();
        interest=[];
        $('.con-lick a').each(function(){
            var oindex =$(this).parents('li').index()+3;
            var ocontent =$(this).attr('data-id');
            interest.push({'content':ocontent,'type': oindex});
        })
        if(interest==''){interest='0'}
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/personalDataEdit",
            dataType: 'jsonp',
            data: {
                uid: uid,
                token: token,
                nickname:nickname,
                birthday:birthday,
                height:height,
                weight:weight,
                industry:industry,
                work_field:work_field,
                company:company,
                home_province:home_province,
                home_city:home_city,
                home_district:home_district,
                place:place,
                tags:tags,
                interest:interest,
                imgs:imgs,
            },
            success: function(data) {
                if(data.error_code == 0) {
                    mui.toast('保存成功！');
                    setTimeout( mui.back() ,1000);
                    var list = plus.webview.currentWebview().opener();
                    mui.fire(list, 'refreshindex');
                    return true;
                } else if(data.error_code == 1001) {
                    setTimeout(function() {
                        exitlogin();
                    },1000);
                } else {
                    if(opper){
                        mui.toast('保存成功！');
                        setTimeout( mui.back() ,1000);
                        var list = plus.webview.currentWebview().opener();
                        mui.fire(list, 'refreshindex');
                        return true;
                    }
                }
            }
        });
    })
     /**
     * captureImage
     * 拍照和相册
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    function captureImage(){
        common.actionSheet('选择上传','取消',[{title:'从相册获取'},{title:'拍照'}],function(index){
            localStorage.camopen="false";
            if(index==1){
                if($('.addVideo').length){
                    mui.toast('不能同时上传图片和视频',{ duration:2000, type:'div' });
                }else{
                    common.galleryImg(function(src){
                        cutImage(src);
                    })
                }
            }else if(index==2){
                if($('.addVideo').length){
                    mui.toast('不能同时上传图片和视频',{ duration:2000, type:'div' });
                }else{
                    common.cameraImg(function(src){
                        cutImage(src);
                    })
                }
            }
        })
    }

    /**
     * @desc 裁剪图片
     * @param src
     */
    function cutImage( src){
      $('.img-cut').addClass('active')
      $('.img-cut-box').html('<img id="img-cut-self" crossorigin="anonymous" src="'+ src +'"/>')

      var image = document.getElementById('img-cut-self')

      cropper = new Cropper(image, {
        aspectRatio: 1 / 1,
        rotatable: false,
        scalable: false,
        minCropBoxWidth: 200,
        minCropBoxHeight: 200
      })
    }

     /**
     * uplode
     * 上传图片返回参数
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    function uplode(dataURL){
        // var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/users_img/UsersImgAdd",
       if (uplodeBlock) return
       uplodeBlock = true
       var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/users_img/saveBase64Image",
        { method:"POST",blocksize:20480,priority:100 },
            function (t, status) { //上传完成
                common.loadingOut();
                if (status == 200) {
                  if (common.IsJsonString(t.responseText)) {
                    var data = JSON.parse(t.responseText)
                    var id = data.id
                    var src = DOMAIN_NAME + data.url
                    // imgs.push(src)
                    $('.editdata .add-img').before('<div class="box-img" data-imgid="' + id + '"><img src="' + src + '"></div>');
                    mui.toast('添加成功', { duration: 2000, type: 'div' });
                    opper = true;
                  } else {
                    mui.toast('上传失败', { duration: 2000, type: 'div' });
                  }
                }else{
                    mui.toast('上传失败',{ duration:2000, type:'div' });
                }
              closeImgCut()
              uplodeBlock = false
            }

        );
        common.loadingIn();
        task.addData("uid", uid);
        task.addData("token",token);
        task.addData("base",dataURL);
        // task.addFile(src, {key: "imgs"});
        mui.toast('开始上传',{ duration:2000, type:'div' });
        task.start();
    }

    /**
     * @desc 关闭浮层
     */
    function closeImgCut() {
      $('.img-cut-box').empty()
      $('.img-cut').removeClass('active')
    }
     /**
     * labellard
     * 标签加载
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    function labellard(othis,otype){
        var arre=[];
        othis.find('.bq-a a').each(function(){
            arre.push($(this).text())
        })
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/category/getCagegoryList",
            dataType: 'jsonp',
            data: {
                uid: uid,
                token: token,
                type:otype,
            },
            success: function(data) {
                if(data.error_code == 0) {
                    var ohtml ='',otitle,oac='';
                    if(othis.attr('class')=='biaoqian-p'){
                        otype==3 ? otitle='我喜欢的运动' : otype==4 ?otitle='我喜欢的音乐' : otype==5 ?otitle='我喜欢的食物' : otype==6?otitle='我喜欢的电影' : otype==7 ?otitle='我喜欢的书和漫画' : otype==8 ?otitle='我的旅行足迹' :otitle='我的标签'  ;
                        $('.table-view3 .title-p').html(otitle);
                        ohtml ='<a class="inf add-inf">+创建自己的标签</a>';
                        for(var i=0 ; i<data.data.length ; i++){
                            var ocon =data.data[i].name;
                            if(arre.indexOf(ocon)> -1 ){
                                var a = arre.indexOf(ocon);
                                arre.splice(a,1);
                                oac="active";
                            }
//                          else if(data.data[i].selected==1){
//                              oac="active";
//                          }
                            else{
                                oac='';
                            }
                            ohtml+='<a class="table-view-cell-a '+oac+'" data-cateid="'+data.data[i].name+'"><em class="ocheckbox"></em>'+data.data[i].name+'</a>';
                        }
                        for(var p=0 ; p<arre.length ; p++){
                            ohtml+='<a class="table-view-cell-a active" data-cateid="'+arre[p]+'"><em class="ocheckbox"></em>'+arre[p]+'</a>';
                        }
                        $('.table-view3 .table-con').html(ohtml);
                        $('.table-view3').css({display:'block'});
                        $('.popover-img').css({display:'block'});
                    }else{
                        for(var i=0 ; i<data.data.length ; i++){
                            for(var j=0 ; j<arre.length ; j++){
                                if(arre[j]==data.data[i].name){arre.splice(j)}
                            }
                            ohtml+='<a class="table-view-cell-a" data-cateid="'+data.data[i].cateid+'">'+data.data[i].name+'</a>';
                        }
                        otype==1 ? $('.table-view2 .title-p').html('行业') : $('.table-view2 .title-p').html('工作领域');
                        $('.table-view2 .table-con').html(ohtml);
                    }
                } else if(data.error_code == 1001) {
                    setTimeout(function() {
                        exitlogin();
                    },1000);
                } else {

                }
            }
        });
    }
    //查看图片
    $('.editdata').on('tap','.box-img',function(){
        var imgid =$(this).find('img').attr('src');
        $('.img-look').addClass('active');
        $('.img-look-box').html('<img src="'+imgid+'"/>')
    })
    $('.img-look').on('tap',function(){
        $(this).removeClass('active');
        $(this).find('img').remove();
    })
    /**
     *
     * 删除图片
     * @cc
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int
     * @return   void
     */
    $('.editdata').on('longtap','.box-img',function(){
        var imgid =$(this).attr('data-imgid');
        var othis =$(this);
        mui.confirm('您确定删除这张图片？','提示',['确定','取消'],function(e){
            if(e.index==0){
                $.ajax({
                    type: "post",
                    url: DOMAIN_NAME + "/index.php/api/users_img/UsersImgDel",
                    dataType: 'jsonp',
                    data: {
                        uid: uid,
                        token: token,
                        id:imgid,
                    },
                    success: function(data) {
                        if(data.error_code == 0) {
                            othis.remove();
                            mui.toast('删除成功');
                        } else if(data.error_code == 1001) {
                            setTimeout(function() {
                                exitlogin();
                            },1000);
                        } else {
                        }
                    }
                });
            }
        },'div')
    })